package io.mvvm.controller;

import io.mvvm.common.constant.SystemConstants;
import io.mvvm.common.enumerate.ResponseEnum;
import io.mvvm.common.entity.AjaxResponse;
import io.mvvm.security.global.ForciblyLoginException;
import io.mvvm.security.utils.JwtUtil;
import io.mvvm.utils.RedisUtil;
import io.mvvm.ws.entity.SendMessageEntity;
import io.mvvm.ws.enumerate.SendMessageTypeEnum;
import io.mvvm.ws.utils.SendMessageUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @program: seize-login
 * @description:
 * @author: 潘
 * @create: 2021-05-15 04:17
 **/
@RestController
public class ForciblyLogin {

    @Resource
    private RedisUtil redisUtil;

    @GetMapping("/forciblyLogin")
    public AjaxResponse forciblyLogin(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization_back");
        if (null == authHeader || authHeader.split("\\.").length != 3) {
            throw new ForciblyLoginException();
        }

        String username = JwtUtil.parseToken(authHeader, "_secret");
        String loginStatusBack = SystemConstants.append(SystemConstants.LOGIN_STATUS_BACK, username);
        String token = (String) redisUtil.get(loginStatusBack);
        if (token.equals(authHeader)) {
            redisUtil.del(loginStatusBack);
            redisUtil.set(SystemConstants.append(SystemConstants.LOGIN_STATUS, username), token);
            SendMessageEntity entity = SendMessageEntity.builder()
                    .userId(new ArrayList<>(Collections.singletonList(username)))
                    .messageType(SendMessageTypeEnum.USER_OFFLINE)
                    .build();
            SendMessageUtil.send(entity);
        }
        return AjaxResponse.success(ResponseEnum.FORCIBLY_LOGIN_SUCCESS, null, token);
    }

}
